//
// Created by suzhen on 16-11-10.
//

#include "CountDownLath.h"

using namespace Concurrent;
USING_ORION_V2

CountDownLath::CountDownLath(std::size_t countTotal)
        : totalCountDown_(countTotal) {
    CHECK(totalCountDown_ > 0) << "totalCountDown_ 必须大于 0 ";
    for (std::size_t i = 0; i < totalCountDown_; ++i) {
        Promise<int> p;
        futureVec_.emplace_back(p.getFuture());
        promiseVec_.emplace_back(std::move(p));
    }
}

void CountDownLath::countDown() {
    std::lock_guard<std::mutex> guard(lock_);
    if (totalCountDown_ == 0) {
        return;
    }
    promiseVec_[--totalCountDown_].setValue(1);
}

void CountDownLath::waitForComplete() {
    std::for_each(futureVec_.begin(), futureVec_.end(), [](Future<int> &f) {
        f.get();
    });
}
